package com.gws.juc;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;


class MyCache{
	private volatile Map<String,Object> map = new HashMap<>();
	private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
	
	
	public void put(String key,String value){
		readWriteLock.writeLock().lock();
		try {
			System.out.println(Thread.currentThread().getName()+" 开始写入数据");
			map.put(key, value);
			TimeUnit.MILLISECONDS.sleep(200);
			System.out.println("写入完成");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally {
			readWriteLock.writeLock().unlock();
		}
	}
	
	public void get(String key){
		readWriteLock.readLock().lock();
		try {
			System.out.println(Thread.currentThread().getName()+"--读取数据");
			TimeUnit.MILLISECONDS.sleep(200);
			System.out.println("读取完成：" + map.get(key));
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			readWriteLock.readLock().unlock();
		}
		
	}
}
/**
 * 读写锁
 * @author gws
 *
 */
public class ReadWriteLockDemo {
	public static void main(String[] args) {
		MyCache myCache = new MyCache();
		
		for (int i = 1; i <= 5; i++) {
			final int n = i;
			new Thread(() -> {
				myCache.put(String.valueOf(n), String.valueOf(n));
			}, String.valueOf(i)).start();
			
		}
		
		for (int i = 1; i <= 5; i++) {
			final int n = i;
			new Thread(() -> {
				myCache.get(String.valueOf(n));
			}, String.valueOf(i)).start();
			
		}
	}

}
